<?php

namespace app\admin\controller;

use app\common\model\MatchesScheduleModel;
use app\common\model\OfflineMsgModel;

class OfflinePushController extends BaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = OfflineMsgModel::field('*');

            if ($operator = trim($this->get('operator', ''))) {
                $model = $model->where('operator', $operator);
            }

            if (in_array($sport_id = $this->get('sport_id', ''), ['1', '2'])) {
                $model = $model->where('sport_id', $sport_id);
            }

            if (in_array($push_status = $this->get('push_status', ''), ['1', '2'])) {
                $model = $model->where('push_status', $push_status);
            }

            if (ctype_digit($match_id = $this->get('match_id', ''))) {
                $model = $model->where('match_id', $match_id);
            }

            if ($creat_time = strtotime($this->get('creat_time', ''))) {
                $model = $model->whereBetween('creat_time', [$creat_time, time()]);
            }

            if ($title = trim($this->get('title', ''))) {
                $model = $model->whereLike('title', $title . '%');
            }

            if ($comp = trim($this->get('comp', ''))) {
                $model = $model->whereLike('comp', $comp . '%');
            }

            return json([
                'count' => $model->count(),
                'data' => $model->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) {
                        if ($query->push_time) {
                            $query->push_time = date('Y-m-d H:i:s', $query->push_time);
                        }

                        if ($query->user) {
                            $query->user = strtr($query->user, ['[' => '', ']' => '', '"' => '', "'" => '']);
                        }
                    })->toArray(),
                'code' => 0,
            ]);
        }


        return $this->fetch();
    }

    public function edit()
    {
        if (!ctype_digit($id = $this->get('id', ''))) {
            return static::bulidFail('ID无效');
        }

        if (!$model = OfflineMsgModel::where('id', $id)->find()) {
            return static::bulidFail('您编辑的内容不存在');
        }

        if ($this->request->isAjax()) {
            if (!in_array($sport_id = $this->post('sport_id', ''), ['', '1', '2'])) {
                return static::bulidFail('类型错误');
            }

            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('标题不能为空');
            }

            if (mb_strlen($title) > 15) {
                return static::bulidFail('标题不能超过15个字符');
            }

            if (!$content = trim($this->post('content', ''))) {
                return static::bulidFail('推送内容不能为空');
            }

            if (mb_strlen($content) > 200) {
                return static::bulidFail('推送内容不能超过200个字符');
            }

            if (!in_array($user = $this->post('user', ''), ['0', '1'])) {
                return static::bulidFail('请选择推送类型');
            }

            if ($user == 0) {
                $user_id = json_encode([], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);;
            } else {
                $user_id = $this->post('user_id', '');
                $user_id = explode(',', $user_id);
                foreach ($user_id as $value) {
                    if (!ctype_digit($value)) {
                        return static::bulidFail('用户ID中包含非法字符:' . $value . ' 请使用英文状态下的[,]符号分割');
                    }
                }
                $user_id = json_encode($user_id, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            }

            if (!$push_time = strtotime($this->post('push_time', ''))) {
                return static::bulidFail('预设推送时间错误');
            }

            if ($push_time < time()) {
                return static::bulidFail('预设推送时间小于当前时间');
            }

            $match_id = $this->post('match_id', '');

            if (ctype_digit($match_id)) {
                if ($sport_id) {
                    if (!$matches = MatchesScheduleModel::field('sport_id,match_time,comp')->where('match_id', $match_id)->where('sport_id', $sport_id)->find()) {
                        return static::bulidFail('所属赛事不存在');
                    }
                } else {
                    if (!$matches = MatchesScheduleModel::field('sport_id,match_time,comp')->where('match_id', $match_id)->find()) {
                        return static::bulidFail('所属赛事不存在');
                    }
                }

                if ($push_time > $matches->match_time) {
                    //return static::bulidFail('预设推送时间大于赛事时间');
                }
                $comp = $matches->comp;
                $sport_id = $matches->sport_id;
            } else if ($match_id != '') {
                return static::bulidFail('所属赛事错误');
            } else {
                $comp = '';
            }

            $model->title = $title;
            $model->sport_id = $sport_id;
            $model->content = $content;
            $model->user = $user_id;
            $model->push_time = $push_time;
            $model->comp = $comp;
            $model->match_id = $match_id;
            $model->operator = $this->admin_name;

            if (!$model->save()) {
                return static::bulidFail('编辑失败');
            }

            return static::bulidSuccess([], '编辑成功');
        }

        $model->push_time = date('Y-m-d H:i:s', $model->push_time);
        $model->is_user = (json_decode($model->user, true) ?? []) ? true : false;
        $model->user = strtr($model->user, ['[' => '', ']' => '', '"' => '', "'" => '']);
        return $this->assign([
            'matches_schedule' => $matches_schedule = MatchesScheduleModel::field('id,match_id,sport_id,comp,match_time')
                ->where('match_status', 2)
                ->group('comp')
                ->select()
                ->toArray(),
            'matches_schedule_json' => json_encode(array_column($matches_schedule, null, 'match_id')),
            'model' => $model,

        ])->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            if (!in_array($sport_id = $this->post('sport_id', ''), ['', '1', '2'])) {
                return static::bulidFail('类型错误');
            }

            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('标题不能为空');
            }

            if (mb_strlen($title) > 15) {
                return static::bulidFail('标题不能超过15个字符');
            }

            if (!$content = trim($this->post('content', ''))) {
                return static::bulidFail('推送内容不能为空');
            }

            if (mb_strlen($content) > 200) {
                return static::bulidFail('推送内容不能超过200个字符');
            }

            if (!in_array($user = $this->post('user', ''), ['0', '1'])) {
                return static::bulidFail('请选择推送类型');
            }

            if ($user == 0) {
                $user_id = json_encode([], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);;
            } else {
                $user_id = $this->post('user_id', '');
                $user_id = explode(',', $user_id);
                foreach ($user_id as $value) {
                    if (!ctype_digit($value)) {
                        return static::bulidFail('用户ID中包含非法字符:' . $value . ' 请使用英文状态下的[,]符号分割');
                    }
                }
                $user_id = json_encode($user_id, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            }

            if (!$push_time = strtotime($this->post('push_time', ''))) {
                return static::bulidFail('预设推送时间错误');
            }

            if ($push_time < time()) {
                return static::bulidFail('预设推送时间小于当前时间');
            }

            $match_id = $this->post('match_id', '');

            if (ctype_digit($match_id)) {
                if ($sport_id) {
                    if (!$matches = MatchesScheduleModel::field('sport_id,match_time,comp')->where('match_id', $match_id)->where('sport_id', $sport_id)->find()) {
                        return static::bulidFail('所属赛事不存在');
                    }
                } else {
                    if (!$matches = MatchesScheduleModel::field('sport_id,match_time,comp')->where('match_id', $match_id)->find()) {
                        return static::bulidFail('所属赛事不存在');
                    }
                }

                if ($push_time > ($matches->match_time + (3600 * 3))) {
                    //return static::bulidFail('预设推送时间最迟在开赛三小时内');
                }
                $comp = $matches->comp;
                $sport_id = $matches->sport_id;
            } else if ($match_id != '') {
                return static::bulidFail('所属赛事错误');
            } else {
                $comp = '';
            }

            $model = new OfflineMsgModel();
            $model->title = $title;
            $model->sport_id = $sport_id;
            $model->content = $content;
            $model->user = $user_id;
            $model->push_time = $push_time;
            $model->comp = $comp;
            $model->push_status = 1;
            $model->match_id = $match_id;
            $model->operator = $this->admin_name;

            if (!$model->save()) {
                return static::bulidFail('添加失败');
            }

            return static::bulidSuccess([], '添加成功');
        }
        return $this->assign([
            'matches_schedule' => $matches_schedule = MatchesScheduleModel::field('id,match_id,sport_id,comp,match_time')
                ->where('match_status', 2)
                ->group('comp')
                ->select()
                ->toArray(),
            'matches_schedule_json' => json_encode(array_column($matches_schedule, null, 'match_id')),
        ])->fetch();
    }


    public function push()
    {
        if (!ctype_digit($id = $this->post('id', ''))) {
            return static::bulidFail('需要推送的消息 ID 无效');
        }

        if (!$model = OfflineMsgModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的消息推送内容');
        }

        $model->push_time = time() + 120;

        if (!$model->save()) {
            return static::bulidFail('立即推送失败');
        }

        return static::bulidSuccess([], '推送成功 消息将在两分钟后推送');
    }


    public function del()
    {
        if (!ctype_digit($id = $this->post('id', ''))) {
            return static::bulidFail('删除的 ID 无效');
        }

        if (!$model = OfflineMsgModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的消息推送内容');
        }

        if (!$model->delete()) {
            return static::bulidFail('删除失败');
        }

        return static::bulidSuccess([], '删除成功');
    }
}
